package com.cn.lp.openapi.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;

public class CGlibPropertyAccessor implements GPropertyAccessor {

	private String name;
	private String alias;
	private GMethod reader;
	private GMethod writer;
	private Class<?> type;

	public String getName() {
		return name;
	}

	@Override
	public String getAlias() {
		return alias;
	}

	public void setAlias(String alias) {
		this.alias = alias;
	}

	public boolean isReadable() {
		return reader != null;
	}

	public boolean isWritable() {
		return writer != null;
	}

	public Class<?> getPropertyType() {
		return type;
	}

	public Object getPropertyValue(Object instance) throws InvocationTargetException {
		if (instance == null)
			return null;
		if (reader == null)
			throw new UnsupportedOperationException(instance.getClass() + "不支持 [" + name + "] 属性 Getter 方法");
		return reader.invoke(instance, new Object[] { type });
	}

	protected void setName(String name) {
		this.name = name;
	}

	protected void setReader(GMethod reader) {
		this.reader = reader;
	}

	protected void setWriter(GMethod writer) {
		this.writer = writer;
	}

	protected void setType(Class<?> type) {
		this.type = type;
	}

	public void setPropertyValue(Object instance, Object value) throws InvocationTargetException {
		if (instance == null)
			return;
		if (writer == null)
			throw new UnsupportedOperationException(instance.getClass() + "不支持 [" + name + "] 属性 Setter 方法");
		writer.invoke(instance, new Object[] { value });
	}

	public Type getGenericType() {
		if (reader != null) {
			return reader.getJavaMethod().getGenericReturnType();
		} else if (writer != null) {
			return writer.getJavaMethod().getGenericParameterTypes()[0];
		}
		return null;
	}

}
